import React, { useEffect } from 'react';
import { useState, useMemo } from 'react';
import { ProFormSelect } from '@ant-design/pro-form';
import { fetchTable, fetch } from '@/services/commCRUD';
import type { ProFormInstance } from '@ant-design/pro-form';
import _ from 'lodash';
// 属性类型
type PropField = {
  /** 控件显示的标题 */
  label: string;
  /** 控件名称 */
  name: string;
  /** 后台查询数据的参数 */
  fetch: API.SearchParams;
  /** 占位符 */
  placeholder?: string;
  /** 控制大小的属性 */
  colProps?: Record<string, number>;
  /** 默认值 */
  value?: string;
  /** 是否禁用 */
  disabled?: boolean;
  /** 验证规则 */
  rules?: API.Rule[];
  /** 控件的宽度 */
  width?: number | 'sm' | 'md' | 'xl' | 'xs' | 'lg';
  /** 是否有全部选项 */
  hasAll?: boolean;
  /** form引用 */
  formRef?: React.MutableRefObject<ProFormInstance<any> | undefined>;
  /** 输入变化时的回调 */
  onChange?: (val: string) => Promise<void>;
  /** 选择搜索项时的回调 */
  onSelect?: (row: Record<string, any>) => Promise<void>;
};
const SearchInputPro: React.FC<PropField> = (props) => {
  const [listData, setListData] = useState<Record<string, any>[]>();
  const [value, setValue] = useState<string>('');
  //设置初始值
  useEffect(() => {
    if (!props.value) {
      return;
    }
    const { tableName, valueTpl, optionTpl, isDao } = props.fetch;
    if (isDao) {
      const whereCause: API.WhereCause = {
        WhereItems: [{ FieldName: valueTpl, Operator: '=', FieldValues: '' + props.value }],
        RelationSign: 'OR',
      };
      fetch(tableName, 1, 10, [], [whereCause], 0)
        .then(function (data) {
          setListData(data.Objectlist);
          if (data.Count > 0) {
            setValue(data.Objectlist[0][optionTpl]);
          }
        })
        .catch(function (ex) {
          console.log('请求出错', tableName, '错误', ex);
        });
    } else {
      fetchTable(tableName, valueTpl, optionTpl, [valueTpl], props.value!)
        .then(function (data) {
          setListData(data);
        })
        .catch(function (ex) {
          console.error('请求', tableName, '错误', ex);
        });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const handleSelect = (val: string) => {
    const rowData = listData?.find((row) => '' + row[props.fetch.valueTpl] === val);
    if (!rowData) {
      return;
    }
    if (props.onSelect) {
      props.onSelect(rowData!);
    }
  };
  const searchChange = (val: string) => {
    if (_.isEmpty(val)) {
      return;
    }
    if (val.replace(/(^\s*)|(\s*$)/g, '') === '') {
      return;
    }
    const { tableName, valueTpl, optionTpl, searchColumns, isDao } = props.fetch;
    if (isDao) {
      const whereCause: API.WhereCause = { WhereItems: [], RelationSign: 'OR' };
      let sc = searchColumns;
      if (!sc) {
        sc = [optionTpl];
      }
      sc.map((c) =>
        whereCause.WhereItems.push({ FieldName: c, Operator: 'like', FieldValues: val }),
      );
      fetch(tableName, 1, 10, [], [whereCause], 0)
        .then(function (data) {
          setListData(data.Objectlist);
        })
        .catch(function (ex) {
          console.log('请求出错', ex);
        });
    } else {
      fetchTable(tableName, valueTpl, optionTpl, searchColumns!, val)
        .then(function (data) {
          if (props.hasAll) {
            setListData([...data, { [valueTpl]: '#all', [optionTpl]: '全部' }]);
          } else {
            setListData(data);
          }
        })
        .catch(function (ex) {
          console.error('请求', tableName, '错误', ex);
        });
    }
  };
  const handleChange = (val: string) => {
    if (props.onChange) {
      props.onChange(val);
    }
    if (_.isEmpty(val) || val.replace(/(^\s*)|(\s*$)/g, '') === '') {
      setValue('');
      return;
    }
    setValue(val);
    if (listData && listData.length === 1) {
      if (props.onSelect) {
        props.onSelect(listData[0]);
      }
    }
  };
  const options = useMemo(() => {
    if (_.isEmpty(listData)) {
      return [];
    }
    return listData!.map((d: object) => {
      return { value: '' + d[props.fetch.valueTpl], label: d[props.fetch.optionTpl] };
    });
  }, [listData, props.fetch]);
  useEffect(() => {
    if (!_.isEmpty(props.formRef?.current) && !_.isEmpty(options)) {
      props.formRef?.current?.setFieldsValue({ [props.name]: value });
    }
  }, [value, props.formRef, props.name, options]);
  if (options === undefined) {
    return <></>;
  }
  return (
    <ProFormSelect
      key={props.name}
      label={props.label}
      name={props.name}
      rules={props.rules}
      showSearch={true}
      allowClear={false}
      colProps={props.colProps}
      disabled={props.disabled}
      options={options}
      width={props.width}
      fieldProps={{
        placeholder: props.placeholder,
        defaultActiveFirstOption: false,
        showArrow: false,
        filterOption: false,
        onSearch: searchChange,
        onChange: handleChange,
        onSelect: handleSelect,
        notFoundContent: null,
        value: value,
      }}
    />
  );
};
export default SearchInputPro;
SearchInputPro.defaultProps = {
  placeholder: '请输入...',
  disabled: false,
  width: 146,
  hasAll: false,
};
